import React, { useEffect } from 'react'
import { Button, Form, Input, Card ,message } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';

import style from '../index.module.css'
import {postAddHospitalParamsType} from "@/api/hospital/model/hospitalSetTypes"
import {postAddHospitalRequest , getHospitalFromIdRequest,updateHosSetFromIdRequest} from "@/api/hospital/hospitalSet"

export default function AddOrUpdateHosSet() {
    const [form] = Form.useForm() 
    const naviGate = useNavigate()
    //获取数据的唯一id
    const {id} = useParams();
    useEffect( () => {
      if(id){
        const getHosData = async () => {
          const res = await getHospitalFromIdRequest(id)
          form.setFieldsValue(res)
        }
        getHosData()
      }
    },[])

    const postAddHandle = async (fieldValue:postAddHospitalParamsType) => {
        if(id){
          await updateHosSetFromIdRequest({
            ...fieldValue,
            id
          })
          message.success('修改医院成功')
        }else{
          postAddHospitalRequest(fieldValue);
          message.success('添加医院成功')
        }
        

        

        naviGate("/syt/hospital/hospitalSet")
        
    }

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 18 }}
        onFinish = {postAddHandle}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "请输入医院名称" ,transform(value) {
            return value.trim()
          }, }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "请输入医院编号" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "请输入api基础路径" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "请输入联系人姓名" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[{ required: true, message: "请输入联系人手机" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          wrapperCol={{ offset: 3 }}
        >
          <Button type="primary" htmlType="submit" className={style.hospR}>
            提交
          </Button>
          <Button type="default" htmlType="button" onClick = {() => {naviGate(-1)}}>
            返回
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
}

